// 手机号验证（支持最新号段）
export const validatePhone = (rule, value, callback) => {
  const reg =
    /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[189]))\d{8}$/;
  if (!value) {
    return callback(new Error("请输入手机号码"));
  }
  if (!reg.test(value)) {
    return callback(new Error("请输入有效的手机号码"));
  }
  callback();
};

// 邮箱验证（RFC 5322标准）
export const validateEmail = (rule, value, callback) => {
  const reg =
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  if (!value) {
    return callback(new Error("请输入邮箱地址"));
  }
  if (!reg.test(value)) {
    return callback(new Error("请输入有效的邮箱地址"));
  }
  callback();
};

// 身份证验证（严格模式）
export const validateIDCard = (rule, value, callback) => {
  const cityCodes = [
    11, 12, 13, 14, 15, 21, 22, 23, 31, 32, 33, 34, 35, 36, 37, 41, 42, 43, 44,
    45, 46, 50, 51, 52, 53, 54, 61, 62, 63, 64, 65, 71, 81, 82, 91,
  ];

  if (!value) {
    return callback(new Error("请输入身份证号码"));
  }

  // 基本格式校验
  const reg =
    /^\d{6}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[1-2]\d|3[0-1])\d{3}[\dX]$/i;
  if (!reg.test(value)) {
    return callback(new Error("身份证格式不正确"));
  }

  // 地区校验
  if (!cityCodes.includes(parseInt(value.substr(0, 2)))) {
    return callback(new Error("地区编码无效"));
  }

  // 校验码验证
  if (value.length === 18) {
    const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const parity = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
      sum += parseInt(value.charAt(i)) * factor[i];
    }
  }

  callback();
};
